<template>
  <div class="app-container app-content">
    <el-row class="line-bottom" v-show="showSearch">
      <el-col class="form_col">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :size="formItemSize"
          v-show="showSearch"
          :label-width="labelWidth"
        >
          <div id="searchFilter" style="display: flex; flex-wrap: wrap">
            <el-form-item label="区域名称" prop="sheetsName">
              <el-input
                :size="formItemSize"
                v-model="queryParams.sheetsName"
                placeholder="请输入区域名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="区域编号" prop="sheetsCode">
              <el-input
                :size="formItemSize"
                v-model="queryParams.sheetsCode"
                placeholder="请输入区域编号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="详细地址" prop="sheetsAddr">
              <el-input
                :size="formItemSize"
                v-model="queryParams.sheetsAddr"
                placeholder="请输入详细地址"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="区域描述" prop="details">
              <el-input
                :size="formItemSize"
                v-model="queryParams.details"
                placeholder="请输入区域描述"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </div>
        </el-form>
      </el-col>

      <el-col class="form_query">
        <el-button
          v-show="collapseAble"
          type="text"
          @click="shiftCollapseAble"
          class="text"
        >
          <span>
            {{ fold ? "收起筛选" : "更多筛选" }}
          </span>
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basedata:meterSheets:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="6">
        <el-alert
          title="每新增一个水司客户，需要新建该客户专用的通用区域！"
          type="warning"
          :closable="false"
        >
        </el-alert>
      </el-col>

      <RightDropdown
        :columns="columns"
        :showSearch.sync="showSearch"
        @queryTable="getList"
        @export="handleExport"
      ></RightDropdown>
    </el-row>

 <!-- <recycle-scroller
    class="scroller"
    :buffer="1000"
    :prerender="200"
   
    :item-size="80"
    key-field="id"
    :items="sheetsList">
   
  <template v-slot="{ item, index }"> -->
    <virtual-scroll
  :data="sheetsList"
  :item-size="62"
  key-prop="id"
  @change="(renderData) => virtualList = renderData">

    <el-table
      v-loading="loading"
      :data="sheetsList"
      size="mini"
      row-key="id"
      border
      :height="getAvailableHeight"
      :lazy="true"
      :load="loadChildren"
      ref="multipleTable"
      :default-expand-all="false"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        label="区域名称"
        align="left"
        prop="sheetsName"
        min-width="200"
        v-if="columns[0].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="区域主键"
        align="left"
        prop="id"
        width="120"
        v-if="columns[6].visible"
      />
      <el-table-column
        label="区域编号"
        align="left"
        prop="sheetsCode"
        width="200"
        v-if="columns[1].visible"
      />
      <el-table-column
        label="区域类型"
        align="left"
        prop="deviceType"
        v-if="columns[2].visible"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.device_type"
            :value="scope.row.deviceType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="经度"
        align="left"
        prop="lng"
        v-if="columns[8].visible"
      />
      <el-table-column
        label="纬度"
        align="left"
        prop="lat"
        v-if="columns[9].visible"
      />
      <el-table-column
        label="详细地址"
        align="left"
        prop="sheetsAddr"
        v-if="columns[3].visible"
      />
      <el-table-column
        label="区域描述"
        align="left"
        prop="details"
        v-if="columns[4].visible"
      />
      <el-table-column
        label="所属客户"
        align="left"
        prop="deptName"
        v-if="columns[7].visible"
      >

      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        v-if="columns[5].visible"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="100"
      >
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="添加下级" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleAdd(scope.row)"
              v-hasPermi="['basedata:meterSheets:add']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="修改" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.parentId !== 0"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['basedata:meterSheets:edit']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="区域设备配置" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-setting"
              @click="handleSetting(scope.row)"
              v-hasPermi="['basedata:meterSheets:edit']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['basedata:meterSheets:remove']"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    </virtual-scroll>
    <!-- </template>

</recycle-scroller> -->

    <!--    <pagination-->
    <!--        v-show="total>0"-->
    <!--        :total="total"-->
    <!--        :page.sync="queryParams.pageNum"-->
    <!--        :limit.sync="queryParams.pageSize"-->
    <!--        @pagination="getList"-->
    <!--    />-->

    <!-- 添加或修改区域管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item
          label="父级区域"
          prop="parentId"
          v-if="title === '添加区域管理'"
        >
          <treeselect
            v-model="form.parentId"
            :options="parentMeterSheetsOptions"
            :normalizer="normalizer"
            placeholder="请选择父级区域"
          />
        </el-form-item>
        <el-form-item label="区域名称" prop="sheetsName">
          <el-input v-model="form.sheetsName" placeholder="请输入区域名称" />
        </el-form-item>
        <!--        <el-form-item label="区域类型" prop="deviceType">-->
        <!--          <el-select v-model="form.deviceType" placeholder="请选择区域类型" style="width: 100%" :disabled="disabledDeviceType" v-show="systemID === 1">-->
        <!--            <el-option v-for="dict in dict.type.sheets_metered" :key="dict.value" :label="dict.label"-->
        <!--                       :value="parseInt(dict.value)"></el-option>-->
        <!--          </el-select>-->
        <!--          <el-select v-model="form.deviceType" placeholder="请选择区域类型" style="width: 100%" :disabled="disabledDeviceType" v-show="systemID === 2">-->
        <!--            <el-option v-for="dict in dict.type.sheets_terminal" :key="dict.value" :label="dict.label"-->
        <!--                       :value="parseInt(dict.value)"></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item
          label="区域类型"
          prop="deviceType"
          v-if="title === '添加区域管理'"
        >
          <el-select
            v-model="form.deviceType"
            placeholder="请选择区域类型"
            style="width: 100%"
            :disabled="disabledDeviceType"
            v-show="systemID === 2"
            @change="handleDeptChange"
          >
            <el-option
              v-for="dict in dict.type.sheets_terminal"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
          <el-select
            v-model="form.deviceType"
            placeholder="请选择区域类型"
            style="width: 100%"
            :disabled="disabledDeviceType"
            v-show="systemID === 1"
            @change="handleDeptChange"
          >
            <el-option
              v-for="dict in dict.type.sheets_metered"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="所属客户"
          prop="tenantId"
          v-show="currentSheetsType === 1 && title === '添加区域管理'"
          :rules="
            currentSheetsType === 1
              ? { required: true, message: '请选择区域', trigger: 'change' }
              : { required: false, message: '请选择区域', trigger: 'change' }
          "
        >
          <el-select
            filterable
            v-model="form.tenantId"
            placeholder="请选择所属客户"
            style="width: 100%"
          >
            <el-option
              v-for="dept in deptOption"
              :key="dept.tenantId"
              :label="dept.deptName"
              :value="dept.tenantId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经度" prop="lng">
          <el-input v-model="form.lng" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="详细地址" prop="sheetsAddr">
          <el-input v-model="form.sheetsAddr" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="区域描述" prop="details">
          <el-input v-model="form.details" placeholder="请输入区域描述" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 区域设备配置 -->
    <el-dialog
      :title="setTitle"
      :visible.sync="setOpen"
      width="700px"
      :close-on-click-modal="false"
      append-to-body
    >
      <div style="height: 400px">
        <el-form ref="setForm" label-width="0px" style="display: flex">
          <el-form-item label="" prop="">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              @click="handleTerminalAdd"
              >新增</el-button
            >
          </el-form-item>
          <el-form-item label="" prop="" style="margin-left: 10px">
            <el-select
              v-model="powerType"
              placeholder="请选择"
              style="width: 200px"
              @change="handleHookTypeChange"
            >
              <el-option
                v-for="item in powerTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-table
          v-loading="setLoading"
          :data="setDataList"
          size="mini"
          row-key="id"
          border
          height="calc(100% - 50px)"
        >
          <el-table-column
            label="设备名称"
            align="center"
            prop="terminalName"
            min-width="150"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="设备编号"
            align="center"
            prop="terminalId"
            width="100"
          />
          <el-table-column
            label="能耗类型"
            align="center"
            prop="hookType"
            width="80"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.hookType == 1 ? "电" : "水" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="运算规则"
            align="center"
            prop="used"
            width="100"
          >
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.used"
                placeholder="请选择"
                style="width: 100%"
                @change="handleEditChange(scope.row)"
              >
                <el-option
                  v-for="dict in dict.type.calc_role"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="使用状态"
            align="center"
            prop="terminalMark"
            width="100"
          >
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.terminalMark"
                placeholder="请选择"
                style="width: 100%"
                @change="handleEditChange(scope.row)"
              >
                <el-option
                  v-for="dict in dict.type.used_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="100"
          >
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="删除" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleBindTerminalDelete(scope.row)"
                >
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div> -->
    </el-dialog>

    <!-- 区域设备配置-新增按钮弹框 -->
    <el-dialog
      title="选取设备"
      :visible.sync="terminalOpen"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <div style="height: 400px">
        <el-form
          ref="terminalForm"
          :model="terminalQueryParams"
          label-width="70px"
          style="display: flex"
        >
          <el-form-item label="用户名称" prop="userName">
            <el-input
              :size="formItemSize"
              v-model="terminalQueryParams.userName"
              placeholder="请输入设备名称"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="设备编号"
            prop="terminalId"
            style="margin-left: 10px"
          >
            <el-input
              :size="formItemSize"
              v-model="terminalQueryParams.terminalId"
              placeholder="请输入设备编号"
              clearable
            />
          </el-form-item>
          <div style="margin-left: 10px; height: 30px; line-height: 36px">
            <el-button
              type="primary"
              plain
              icon="el-icon-search"
              @click="handleTerminalQuery"
              size="mini"
              >查询</el-button
            >
          </div>
        </el-form>
        <el-table
          v-loading="terminalLoading"
          :data="terminalDataList"
          size="mini"
          row-key="id"
          border
          height="calc(100% - 102px)"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="用户名称"
            align="center"
            prop="userName"
            min-width="150"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="设备编号"
            align="center"
            prop="terminalId"
            width="120"
          />
          <el-table-column
            label="能耗分类"
            align="center"
            prop="hookType"
            width="100"
          >
            <template slot-scope="scope">
              <span>{{ powerType == 1 ? "电" : "水" }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="terminalTotal > 0"
          :total="terminalTotal"
          :page.sync="terminalQueryParams.pageNum"
          :limit.sync="terminalQueryParams.pageSize"
          @pagination="getTerminalDataList"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="terminalSubmitForm">确 定</el-button>
        <el-button @click="terminalCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptList } from "@/api/system/dept.js";
import { getAreaTree } from "@/api/tree/index";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  listMeterSheetsTree,
  getMeterSheets,
  delMeterSheets,
  addMeterSheets,
  updateMeterSheets,
  getBindTerminalList,
  removeBindTerminal,
  addBindTemrinal,
  editBindTemrinal,
} from "@/api/basedata/meterSheets";
import { listElecTerminalXb } from "@/api/basedata/elecTerminalXb";
import { gjListTerminalxb } from "@/api/record/terminalxb";
import { getSheetsTree, getAreaTreeChildren } from "../../../api/tree";
import { mapState } from "vuex";
import { Notification, MessageBox, Message, Loading } from 'element-ui'

export default {
  name: "Sheets",
  components: { Treeselect },
  dicts: [
    "sheets_metered",
    "sheets_terminal",
    "device_type",
    "used_status",
    "calc_role",
  ],
  data() {
    return {
       items: [
      { id: 1, label: '选项1' },
      { id: 2, label: '选项2' }
    ],

      // showDeptFormItem: false,
      // 当前选择的区域类型
      currentSheetsType: null,
      // 所属客户
      deptOption: [],
      disabledDeviceType: false,
      screenHeight: null,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 区域管理表格数据
      sheetsList: [],
      sheetsListCopy: [],
      maps: new Map(),
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        sheetsName: null,
        sheetsCode: null,
        sheetsAddr: null,
        treeType: null,
        details: null,
      },
      // 列信息
      columns: [
        { key: 1, label: `区域名称`, visible: true, dataindex: "sheetsName" },
        { key: 2, label: `区域编号`, visible: true, dataindex: "sheetsCode" },
        { key: 3, label: `区域类型`, visible: true, dataindex: "deviceType" },
        { key: 4, label: `详细地址`, visible: true, dataindex: "sheetsAddr" },
        { key: 5, label: `区域描述`, visible: true, dataindex: "details" },
        { key: 6, label: `备注`, visible: true, dataindex: "remark" },
        { key: 7, label: `区域主键`, visible: true, dataindex: "id" },
        { key: 8, label: `所属客户`, visible: true, dataindex: "deptName" },
        { key: 9, label: `经度`, visible: true, dataindex: "lng" },
        { key: 10, label: `纬度`, visible: true, dataindex: "lat" },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "请选中父级区域", trigger: "blur" },
        ],
        sheetsName: [
          { required: true, message: "区域名称不能为空", trigger: "blur" },
        ],
        deviceType: [
          { required: true, message: "区域类型不能为空", trigger: "blur" },
        ],
      },
      parentMeterSheetsOptions: [],
      maxShow: 4,
      formItemSize: "mini",
      collapseAble: false,
      fold: false,
      labelWidth: "80px",
      //区域设备配置
      // 弹出层标题
      setTitle: "",
      // 是否显示弹出层
      setOpen: false,
      powerType: 1,
      powerTypeOption: [
        { label: "电", value: 1 },
        { label: "水", value: 2 },
      ],
      setLoading: false,
      setDataList: [],
      selectedAreaId: null,
      selectedAreaName: "",
      terminalOpen: false,
      terminalTotal: 0,
      terminalQueryParams: {
        pageNum: 1,
        pageSize: 20,
        terminalId: "",
        userName: "",
      },
      terminalLoading: false,
      terminalDataList: [],
      selectedTerminalList: [],
    };
  },
  watch: {
    systemID(val) {
      this.getList();
    },
  },
  created() {
    this.getList();
    this.screenHeight = document.body.clientHeight;
  },
  computed: {
    ...mapState({
      systemID: (state) => state.permission.systemID,
    }),
    // systemID() {
    //   return this.$store.state.permission.systemID
    // },
    getAvailableHeight() {
      return this.screenHeight - (this.showSearch ? 200 : 155);
    },
  },
  methods: {
    handleEditChange(row) {
      editBindTemrinal(row).then((response) => {
        this.$modal.msgSuccess("修改成功");
        this.getBindList();
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      let that = this;
      that.selectedTerminalList = [];
      // selectedTerminalList
      for (let i = 0; i < selection.length; i++) {
        let item = selection[i];
        that.selectedTerminalList.push({
          areaId: that.selectedAreaId,
          areaName: that.selectedAreaName,
          terminalId: item.terminalId,
          terminalName: item.userName,
          used: 4,
          hookType: that.powerType,
          terminalMark: 1,
          locationNb: item.locationNb,
        });
      }
    },
    //区域设备配置-选择能耗类型
    handleHookTypeChange(val) {
      this.powerType = val;
      this.getBindList();
    },
    // 所属区域类型选择框change事件
    handleDeptChange(val) {
      this.currentSheetsType = val;
    },
    // 获取所有客户
    getDeptList() {
      deptList().then((response) => {
        this.deptOption = response.data;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.sheetsName,
        children: node.children,
      };
    },
    /** 查询区域管理列表 */
    getList() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        this.queryParams.treeType = "0," + 3; //获取所有的区域信息
        getSheetsTree(this.queryParams)
          .then((response) => {
            if (response.data) {
              this.sheetsList = response.data;
              this.sheetsListCopy = JSON.parse(JSON.stringify(response.data)); // 备份的全量数据
              this.parentMeterSheetsOptions = JSON.parse(
                JSON.stringify(response.data)
              );
              if (
                this.queryParams && (this.queryParams.sheetsName || this.queryParams.sheetsCode || this.queryParams.sheetsAddr ||
                  this.queryParams.details)
              ) {

              } else {
                console.log("***********************");
                console.log(this.sheetsList);
                this.sheetsList.map((item) => {
                  if (item.children.length > 0) {
                    item.hasChildren = true;
                    item.children = [];
                  }
                });
                console.log(this.sheetsList);
              }
            }
            this.loading = false;
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    loadChildren(row, treeNode, resolve) {
      function findNodeById(node, id) {
        // 找到对应id数据
        if (node.id === id) {
          // 拷贝当前节点数据
          const newNode = { ...node };
          if (newNode.children && newNode.children.length > 0) {
            // 修改查找到的对应id的children数据，把找到的数据里面的children数据置空，并设置hasChildren
            newNode.children = newNode.children.map((child) => {
              return {
                ...child,
                // 设置hasChildren判断是否显示展开按钮
                hasChildren: child.children.length > 0 ? true : false,
                children: [], // 置空子节点
              };
            });
          }
          return newNode.children;
        }
        // 递归查找每一层的children数据
        if (node.children && node.children.length > 0) {
          for (let i = 0; i < node.children.length; i++) {
            const result = findNodeById(node.children[i], id);
            if (result) {
              return result;
            }
          }
        }
        return null;
      }
      // 若已加载过子节点，直接返回缓存数据
      if (row.children && row.children.length > 0) {
        resolve(row.children);
        return;
      }
      const foundNode = findNodeById(this.sheetsListCopy[0], row.id);
        if(foundNode  &&  foundNode.length > 200){
        // alert('子节点数超过200，请等待2-5秒！');
        Message.info('子节点数超过200，请等待2-5秒！')
      }
      // Message.info('子节点数超过200，请等待2-5秒！')
      //设置map值，记录当前展开的值，方便后期新增/修改对应行值时修改数据
      // this.maps.set(tree.id, { tree, treeNode, resolve });
      this.maps.set(row.id, { row, treeNode, resolve });
      
      // console.log(8888);
      // console.log(foundNode);
      // Message.info('子节点数超过200，请等待2-5秒！')
    
      resolve(foundNode);
    },
    refresh(parentId) {
      // 根据父级id取出对应节点数据
      const { row, treeNode, resolve } = this.maps.get(parentId);
      this.$set(
        this.$refs.multipleTable.store.states.lazyTreeNodeMap,
        parentId,
        []
      );
      if (row) {
        this.loadChildren(row, treeNode, resolve);
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        deviceType: null,
        tenantId: null,
        sheetsName: null,
        sheetsCode: null,
        details: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.currentSheetsType = null;
      this.disabledDeviceType = false;
      if (row) {
        this.form.parentId = row.id;
      }
      this.open = true;
      this.title = "添加区域管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      debugger;
      const id = row.id;
      const currentRow = row;
      // this.showDeptFormItem = false
      getMeterSheets(id).then((response) => {
        this.form = response.data;
        // this.form.parentId = (response.data.parentId === 'root' ? undefined : response.data.parentId)
        this.open = true;
        this.title = "修改区域管理";
        if (currentRow.children == null || currentRow.children.length === 0) {
          this.disabledDeviceType = false;
        } else {
          this.disabledDeviceType = true;
        }
      });
    },

    //查询设备
    handleTerminalQuery() {
      this.getTerminalDataList();
    },
    /** 设备提交按钮 */
    terminalSubmitForm() {
      addBindTemrinal(this.selectedTerminalList).then((response) => {
        this.$modal.msgSuccess("新增成功");
        this.getBindList();
        this.terminalOpen = false;
      });
    },
    // 设备取消按钮
    terminalCancel() {
      this.terminalOpen = false;
      this.terminalQueryParams = {
        pageNum: 1,
        pageSize: 20,
        terminalId: "",
        userName: "",
        sheetsId: this.selectedAreaId,
      };
    },
    /** 区域设备配置-新增打开弹框 */
    handleTerminalAdd() {
      this.terminalQueryParams = {
        pageNum: 1,
        pageSize: 20,
        terminalId: "",
        userName: "",
        sheetsId: this.selectedAreaId,
      };
      this.terminalOpen = true;
      this.getTerminalDataList();
    },
    getTerminalDataList() {
      this.terminalLoading = true;
      if (this.powerType == 1) {
        listElecTerminalXb(this.terminalQueryParams).then((response) => {
          this.terminalDataList = response.rows;
          this.terminalTotal = response.total;
          this.terminalLoading = false;
        });
      } else {
        gjListTerminalxb(this.terminalQueryParams).then((response) => {
          this.terminalDataList = response.rows;
          this.terminalTotal = response.total;
          this.terminalLoading = false;
        });
      }
    },
    // 区域设备配置
    handleSetting(row) {
      this.setTitle = "[" + row.sheetsName + "]区域设备配置";
      this.setOpen = true;
      this.selectedAreaId = row.id;
      this.selectedAreaName = row.sheetsName;
      this.powerType = 1;
      this.getBindList();
      //打开新页面
      // this.$tab.openPage("["+row.sheetsName+"]区域设备配置", '/archives/sheets/terminal-set/index/' + row.id, {});
    },
    /** 删除按钮操作-区域设备配置 */
    handleBindTerminalDelete(row) {
      const id = row.id;
      this.$modal
        .confirm("是否确认删除所选记录？")
        .then(function () {
          return removeBindTerminal(id);
        })
        .then(() => {
          this.getBindList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    getBindList() {
      //加载数据
      this.setLoading = true;
      getBindTerminalList({
        areaId: this.selectedAreaId,
        hookType: this.powerType,
      }).then((response) => {
        console.log(response);
        if (response.data) {
          this.setDataList = response.data;
        }
        this.setLoading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      // const level = this.findDataLevel(this.form.parentId, this.parentMeterSheetsOptions);
      // if(level >3){
      //   this.$message.error("最多只能添加3级子节点");
      //   return
      // }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateMeterSheets(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.getList().then(() => {
                this.refresh(this.form.parentId);
              });
              this.open = false;
              this.getTerminalTreeList();
              this.getMeteredTreeList();
            });
          } else {
            // this.parentMeterSheetsOptions.filter((item) => {
            //   const deviceType = this.getMeters(item, this.form)
            //   if(deviceType === 1){
            //     return this.$modal.msgWarning("户表区域下不可新建区域");
            //   }
            // })
            const deviceType = this.findDeviceType(
              this.parentMeterSheetsOptions,
              this.form.parentId
            );
            if (deviceType === 1) {
              return this.$modal.msgWarning("户表区域下不可新建区域");
            }
            addMeterSheets(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.getList().then(() => {
                this.refresh(this.form.parentId);
              });
              this.open = false;
              this.getTerminalTreeList();
              this.getMeteredTreeList();
            });
          }
        }
      });
    },
    // 获取大用户区域树
    getTerminalTreeList() {
      let treeType = "0,2";
      getAreaTree(treeType).then((response) => {
        localStorage.setItem("terminalTreeData", JSON.stringify(response.data));
      });
    },
    // 获取户表区域树
    getMeteredTreeList() {
      let treeType = "0,1";
      getAreaTree(treeType).then((response) => {
        localStorage.setItem("meteredTreeData", JSON.stringify(response.data));
      });
    },
    // 判断父级区域是哪种类型
    findDeviceType(data, parentId) {
      let res_deviceType = "";
      for (let i = 0; i < data.length; i++) {
        if (data[i].id === parentId) {
          res_deviceType = data[i].deviceType;
          break;
        }
        if (data[i].children && data[i].children.length > 0) {
          const text = this.findDeviceType(data[i].children, parentId);
          if (text) {
            return text;
          }
        }
      }
      return res_deviceType;
    },
    // findDataLevel(id, list, level = 1){
    //   for(const item of list){
    //     if(item.parentId === id){
    //       return level
    //     }
    //     if(item.children && item.children.length > 0){
    //       return this.findDataLevel(id, item.children,level + 1)
    //     }
    //   }
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.id;
      this.$modal
        .confirm("是否确认删除所选记录？")
        .then(function () {
          return delMeterSheets(IDs);
        })
        .then(() => {
          this.getList().then(() => {
            this.refresh(row.parentId);
          });
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "basedata/meterSheets/export",
        {
          ...this.queryParams,
        },
        `区域信息.xlsx`
      );
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold;
      this.minShowControl();
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(
        `#searchFilter .el-form-item.el-form-item--${this.formItemSize}`
      );
      const len = group?.length ? group?.length : 0;
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold;
          }
        });
        this.collapseAble = true;
      } else {
        this.collapseAble = false;
      }
    },
  },
  mounted() {
    this.getDeptList();
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl();
    }
  },
};
</script>
<style scoped>

.scroller {
  height: 500px; /* 关键：必须设置固定高度，否则组件无法计算可视区域 */
  width: 100%;

}


::v-deep .el-alert {
  padding: 5px 16px;
}
::v-deep .el-dialog__body {
  padding: 10px 30px;
}
.form_col {
  width: 80%;

  ::v-deep .el-form {
    width: 100%;
  }

  ::v-deep .el-form-item {
    width: 20%;
  }
}

.form_query {
  width: 20%;
  text-align: right;
}
.el-form-item {
  margin-bottom: 10px !important;
}
</style>
